package com.drinkian.utils;

import io.jsonwebtoken.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtil {

    private String ENCODE_KEY;
    private long EXPIRATION_TIME;

    public void setENCODE_KEY(String ENCODE_KEY) {
        this.ENCODE_KEY = ENCODE_KEY;
    }

    public void setEXPIRATION_TIME(long EXPIRATION_TIME) {
        this.EXPIRATION_TIME = EXPIRATION_TIME;
    }


    /**
     * 加密
     *
     * @param id
     * @return
     */
    public String getToken(Long id) {
        String token = Jwts.builder()
                // header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                // payload
                .setSubject(String.valueOf(id))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .setNotBefore(new Date())
                .setId(UUID.randomUUID().toString())
                // signature
                .signWith(SignatureAlgorithm.HS256, ENCODE_KEY)
                .compact();
        return token;
    }

    /**
     * token解密
     *
     * @param token
     * @return
     */
    public int parseToken(String token) throws Exception{
        return Integer.parseInt(Jwts.parser().setSigningKey(ENCODE_KEY).parseClaimsJws(token).getBody().getSubject());
    }
}

